<template>
  <div class="home-shop">
    <!-- 主要内容区域 -->
     <div class="detail-content">
    <div class="main-content">
      <!-- 搜索框和分类区域 -->
      <div class="search-section">
        <div class="search-area">
          <input
            type="text"
            placeholder="搜索商品"
            class="search-input"
            v-model="searchKeyword"
            @keyup.enter="handleSearch"
            @input="handleSearchInput"
          >
          <div class="category-tabs">
            <div
              class="category-tab"
              :class="{ active: selectedCategoryId === null }"
              @click="selectCategory(null)"
            >
              全部分类
            </div>
            <div
              v-for="category in categories"
              :key="category.categoryId"
              class="category-tab"
              :class="{ active: selectedCategoryId === category.categoryId }"
              @click="selectCategory(category.categoryId)"
            >
              {{ category.categoryName }}
            </div>
          </div>
      </div>
    </div>

      <!-- 商品展示区域 -->
      <div class="product-area">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <p>正在加载商品数据...</p>
        </div>

        <!-- 没有商品时的提示 -->
        <div v-else-if="products.length === 0" class="no-products-container">
          <p>暂无商品</p>
        </div>

        <!-- 商品网格 -->
        <div v-else class="product-grid">
          <div
            class="product-item"
            v-for="product in products"
            :key="product.productId"
            @click="goToProductDetail(product.productId)"
            style="cursor: pointer"
          >
            <div class="product-img">
              <img v-if="product.productImage" :src="product.productImage" :alt="product.productName" />
              <div v-else class="no-image">暂无图片</div>
            </div>
            <div class="product-name">{{ product.productName }}</div>
            <div class="product-price">￥{{ product.productPrice }}</div>
          </div>
        </div>

        <!-- 分页区域 -->
        <div v-if="!loading && products.length > 0 && total > 0" class="pagination-area">
          <div class="pagination-info">
            <span>Total {{ total }}</span>
            <select v-model="pageSize" @change="handleSizeChange">
              <option value="5">5/page</option>
              <option value="10">10/page</option>
              <option value="15">15/page</option>
              <option value="20">20/page</option>
            </select>
          </div>
          <div class="pagination-controls">
            <button @click="goToPage(currentPage - 1)" :disabled="currentPage <= 1">‹</button>
            <button
              v-for="page in visiblePages"
              :key="page"
              @click="goToPage(page)"
              :class="{ active: page === currentPage }"
            >
              {{ page }}
            </button>
            <button @click="goToPage(currentPage + 1)" :disabled="currentPage >= totalPages">›</button>
          </div>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import http from '@/api/http'

export default {
  name: 'HomeShop',
  setup() {
    const router = useRouter()

    // 商品数据
    const products = ref([])
    const loading = ref(false)

    // 分类数据
    const categories = ref([])
    const selectedCategoryId = ref(null)

    // 搜索数据
    const searchKeyword = ref('')

    // 用户登录状态
    const isLoggedIn = ref(false)

    // 分页相关数据
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(0)

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(total.value / pageSize.value)
    })

    // 计算可见页码
    const visiblePages = computed(() => {
      const pages = []
      const start = Math.max(1, currentPage.value - 2)
      const end = Math.min(totalPages.value, currentPage.value + 2)

      for (let i = start; i <= end; i++) {
        pages.push(i)
      }

      return pages
    })

    // 获取分类数据
    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category/getPublicCategory', {

        })
        if (response.data) {
          categories.value = response.data
        }
      } catch (error) {
        console.error('获取分类数据失败:', error)
        categories.value = []
      }
    }

    // API调用方法
    const fetchProducts = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          status: 1
        }

        // 如果选择了分类，添加分类筛选参数
        if (selectedCategoryId.value !== null) {
          params.categoryId = selectedCategoryId.value
        }

        // 如果有搜索关键词，添加搜索参数
        if (searchKeyword.value && searchKeyword.value.trim()) {
          params.keyword = searchKeyword.value.trim()
        }

        const response = await axios.get('/api/product/query', {

          params: params
        })

        if (response.data) {
          const processedProducts = (response.data.list || []).map(product => ({
            ...product,
            productImage: product.productImage ? product.productImage.trim().replace(/`/g, '') : ''
          }))

          products.value = processedProducts
          total.value = response.data.total || 0
        }
      } catch (error) {
        console.error('获取商品数据失败:', error)
        products.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }

    // 跳转到指定页面
    const goToPage = (page) => {
      if (page < 1 || page > totalPages.value || loading.value) return

      currentPage.value = page
      fetchProducts()
    }

    // 页面大小变化处理
    const handleSizeChange = () => {
      currentPage.value = 1
      fetchProducts()
    }

    // 分类选择处理
    const selectCategory = (categoryId) => {
      selectedCategoryId.value = categoryId
      currentPage.value = 1  // 重置到第一页
      fetchProducts()
    }

    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1  // 重置到第一页
      fetchProducts()
    }

    // 搜索输入处理（实时搜索，可选）
    let searchTimeout = null
    const handleSearchInput = () => {
      // 清除之前的定时器
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }

      // 设置新的定时器，延迟500ms执行搜索
      searchTimeout = setTimeout(() => {
        currentPage.value = 1
        fetchProducts()
      }, 500)
    }

    // 跳转到商品详情页
    const goToProductDetail = (productId) => {
      // 保存当前页面状态到sessionStorage
      const currentState = {
        currentPage: currentPage.value,
        searchKeyword: searchKeyword.value,
        selectedCategoryId: selectedCategoryId.value,
        products: products.value,
        total: total.value,
        scrollTop: window.pageYOffset || document.documentElement.scrollTop
      }
      sessionStorage.setItem('homeShopState', JSON.stringify(currentState))
      router.push(`/product/${productId}`)
    }

    // 检查登录状态
    const checkLoginStatus = () => {
      // 商城首页只检查顾客的登录状态
      const userToken = localStorage.getItem('userToken')
      const userRoles = localStorage.getItem('userRoles')

      // 检查token和roles是否都存在
      if (!userToken || !userRoles) {
        isLoggedIn.value = false
        return
      }

      // 验证是否有CUSTOMER角色
      try {
        const roles = JSON.parse(userRoles)
        const hasCustomerRole = roles.some(role => role.code === 'CUSTOMER')
        isLoggedIn.value = hasCustomerRole
      } catch (error) {
        console.error('解析userRoles失败:', error)
        isLoggedIn.value = false
      }
    }

    // 跳转到登录页面
    const goToLogin = () => {
      router.push('/')
    }

    // Token 验证函数
    const validateToken = async () => {
      try {
        // 检查是否有 token
        const token = localStorage.getItem('userToken') || 
                     localStorage.getItem('Token') || 
                     localStorage.getItem('sellerToken') || 
                     localStorage.getItem('token')
        
        if (!token) {
          console.log('没有找到 token，跳过验证')
          return
        }

        // 发送测试请求验证 token
        await http.get('/user/csToken')
        console.log('Token 验证成功')
      } catch (error) {
        console.error('Token 验证失败:', error)
        
        // 检查是否是 401 错误（Token 无效）
        if (error.response?.status === 401 || 
            error.response?.data?.code === 401 || 
            error.message?.includes('Token 无效')) {
          
          console.log('Token 无效，清空 localStorage')
          
          // 清空所有可能的 token 和用户信息
          localStorage.removeItem('userToken')
          localStorage.removeItem('Token')
          localStorage.removeItem('sellerToken')
          localStorage.removeItem('token')
          localStorage.removeItem('userRoles')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('sellerInfo')
          
          // 更新登录状态
          isLoggedIn.value = false
          
          console.log('localStorage 已清空')
        }
      }
    }


    // 组件挂载时获取数据
    onMounted(async () => {
      // 首先验证 token
      await validateToken()
      
      // 检查是否需要恢复状态
      const shouldRestore = sessionStorage.getItem('shouldRestoreState')
      const savedState = sessionStorage.getItem('homeShopState')
      
      if (shouldRestore === 'true' && savedState) {
        // 恢复状态
        const state = JSON.parse(savedState)
        currentPage.value = state.currentPage
        searchKeyword.value = state.searchKeyword
        selectedCategoryId.value = state.selectedCategoryId
        products.value = state.products
        total.value = state.total
        
        // 获取分类列表（确保数据最新）
        fetchCategories()
        
        // 清除状态标记
        sessionStorage.removeItem('shouldRestoreState')
        sessionStorage.removeItem('homeShopState')
        
        // 恢复滚动位置
        setTimeout(() => {
          if (state.scrollTop) {
            window.scrollTo(0, state.scrollTop)
          }
        }, 100)
      } else {
        // 正常初始化
        fetchCategories()  // 获取分类数据
        fetchProducts()    // 获取商品数据
      }
    })

    return {
      products,
      loading,
      categories,
      selectedCategoryId,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      totalPages,
      visiblePages,
      goToPage,
      handleSizeChange,
      fetchProducts,
      selectCategory,
      handleSearch,
      handleSearchInput,
      goToProductDetail,
      checkLoginStatus,
      goToLogin,
      isLoggedIn
    }
  }
}
</script>

<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 确保 html 和 body 完全覆盖浏览器 */
html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 确保 Vue 应用根元素也完全覆盖 */
#app {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

/* 整体页面布局 */
.home-shop {
  width:100%;
  height: 94.3vh;
  right: 0;
  background: transparent;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  overflow: hidden;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background: linear-gradient(180deg, #468cd1 0%, #34495e 100%);

}

.detail-content {
  max-height: 100vh;
  overflow-y: auto;
}

/* 主要内容区域 */
.main-content {
  width: 100%;
  min-height: 100%;
  padding: 20px;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Logo 区域样式 */
.logo-area {
  padding: 24px 20px;
  text-align: center;
  border-bottom: 2px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.05);
}

.logo {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  border: 3px solid rgba(255, 255, 255, 0.2);
}

.logo-text {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
  margin-top: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

/* 导航项样式 */
.nav-item {
  padding: 20px 24px;
  cursor: pointer;
  background-color: transparent;
  color: rgba(255, 255, 255, 0.9);
  font-size: 15px;
  font-weight: 500;
  text-align: left;
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  position: relative;
}

.nav-item:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  transform: translateX(5px);
}

.nav-item:hover::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
}

/* 搜索和分类区域 */

.search-area {
  display: flex;
  gap: 32px;
  align-items: center;
}

/* 搜索输入框 */
.search-input {
  width: 320px;
  height: 40px;
  padding: 0 16px;
  border: 2px solid transparent;
  border-radius: 25px;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  outline: none;
}

.search-input:focus {
  border-color: #667eea;
  background: rgba(255, 255, 255, 1);
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 8px;
  align-items: center;
}

.category-tab {
  padding: 8px 16px;
  border: 2px solid transparent;
  border-radius: 25px;
  font-size: 14px;
  color: #666666;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-tab:hover {
  border-color: #667eea;
  color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.category-tab.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: transparent;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

/* 用户操作相关的样式已经移至TopNavbar组件 */

/* 商品区域 */
.product-area {
  flex: 1;
  padding: 32px;
  background: transparent;
  overflow-y: auto;
  width: 100%;
  height: 100%;
}

/* 加载和空状态样式 */
.loading-container,
.no-products-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  font-size: 18px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

/* 商品网格 */
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

/* 商品卡片 */
.product-item {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.product-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  border-color: rgba(102, 126, 234, 0.3);
}

/* 商品图片 */
.product-img {
  width: 100%;
  height: 200px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  position: relative;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.product-img:hover img {
  transform: scale(1.05);
}

.no-image {
  color: #999;
  font-size: 14px;
  text-align: center;
}

/* 商品名称 */
.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 商品价格 */
.product-price {
  font-size: 18px;
  font-weight: 700;
  color: #e74c3c;
  margin-bottom: 12px;
}

/* 分页区域 */
.pagination-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  margin-top: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 分页信息 */
.pagination-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-left: 20px;
}

.pagination-info span {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  font-weight: 500;
}

/* 页面大小选择器 */
.pagination-info select {
  padding: 8px 12px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  color: #2c3e50;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  outline: none;
}

.pagination-info select:hover {
  border-color: #667eea;
  background: rgba(255, 255, 255, 1);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.pagination-info select:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 分页控制 */
.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

/* 分页按钮 */
.pagination-controls button {
  width: 36px;
  height: 36px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-controls button:hover:not(:disabled) {
  background: #667eea;
  color: white;
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.pagination-controls button:disabled {
  background: rgba(255, 255, 255, 0.5);
  color: rgba(0, 0, 0, 0.3);
  cursor: not-allowed;
  border-color: rgba(255, 255, 255, 0.2);
}

.pagination-controls button.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: transparent;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
}

.pagination-controls button.active:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.5);
}

/* 退出按钮特殊样式 */
.logout-btn {
  margin-top: auto !important;
  background: rgba(231, 76, 60, 0.1) !important;
  border-top: 2px solid rgba(231, 76, 60, 0.3) !important;
  color: #e74c3c !important;
}

.logout-btn:hover {
  background: rgba(231, 76, 60, 0.2) !important;
  color: #ffffff !important;
  transform: translateX(5px);
}

.logout-btn:hover::before {
  background: linear-gradient(180deg, #e74c3c 0%, #c0392b 100%) !important;
}
</style>
